<template>
  <div class="app-container">
    <div v-loading="loading" class="detail-content">
      <!-- 合同详情部分 -->
      <div class="section">
        <div class="section-header">
          <span class="section-number">1</span>
          <h2>合同详情</h2>
        </div>
        <div class="detail-card">
          <div class="detail-item">
            <span class="label">合同编号：</span>
            <span class="value">{{ contractData.contractNo || "-" }}</span>
          </div>
          <div class="detail-item">
            <span class="label">合同名称：</span>
            <span class="value">{{ contractData.contractName || "-" }}</span>
          </div>
          <div class="detail-item">
            <span class="label">老人姓名：</span>
            <span class="value">{{ contractData.elderly?.name || "-" }}</span>
          </div>
          <div class="detail-item">
            <span class="label">老人身份证号：</span>
            <span class="value">{{ contractData.elderly?.idCard || "-" }}</span>
          </div>
          <div class="detail-item">
            <span class="label">入住单号：</span>
            <span class="value">{{
              contractData.checkInManagement?.checkInNo || "-"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label">合同期限：</span>
            <span class="value">
              {{
                contractData.startDate
                  ? parseTime(contractData.startDate, "{y}-{m}-{d}")
                  : "-"
              }}—
              {{
                contractData.endDate
                  ? parseTime(contractData.endDate, "{y}-{m}-{d}")
                  : "-"
              }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">合同状态：</span>
            <el-tag :type="getStatusType(contractData.contractStatus)">
              {{ getStatusLabel(contractData.contractStatus) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">签约日期：</span>
            <span class="value">{{
              contractData.signTime
                ? parseTime(contractData.signTime, "{y}-{m}-{d}")
                : "-"
            }}</span>
          </div>

          <!-- 丙方信息 -->
          <div v-if="contractData.partyCName" class="detail-item">
            <span class="label">丙方姓名：</span>
            <span class="value">{{ contractData.partyCName }}</span>
          </div>
          <div v-if="contractData.partyCPhone" class="detail-item">
            <span class="label">丙方联系方式：</span>
            <span class="value">{{ contractData.partyCPhone }}</span>
          </div>

          <!-- 额外信息字段 -->
          <div class="detail-item">
            <span class="label">创建人：</span>
            <span class="value">{{
              contractData.sysUser?.nickName || "-"
            }}</span>
          </div>
          <div v-if="contractData.createTime" class="detail-item">
            <span class="label">创建时间：</span>
            <span class="value">{{
              parseTime(contractData.createTime, "{y}-{m}-{d}")
            }}</span>
          </div>
          <div v-if="contractData.extraField1" class="detail-item">
            <span class="label">额外字段1：</span>
            <span class="value">{{ contractData.extraField1 }}</span>
          </div>
          <div v-if="contractData.extraField2" class="detail-item">
            <span class="label">额外字段2：</span>
            <span class="value">{{ contractData.extraField2 }}</span>
          </div>

          <!-- 合同文件 -->
          <div class="detail-item">
            <span class="label">合同文件：</span>
            <span class="value">
              {{ contractData.contractFile || "-" }}
              <el-button
                v-if="contractData.contractFile"
                type="text"
                size="small"
                @click="viewFile(contractData.contractFile)"
              >
                查看
              </el-button>
            </span>
          </div>
        </div>
      </div>

      <!-- 解除记录部分（当合同已失效或已过期时显示） -->
      <div
        v-if="
          (contractData.contractStatus === '2' ||
            getStatusLabel(contractData.contractStatus) === '已过期') &&
          (contractData.terminationSubmitter ||
            contractData.terminationTime ||
            contractData.terminationAgreement)
        "
        class="section"
      >
        <div class="section-header">
          <span class="section-number">2</span>
          <h2>解除记录</h2>
        </div>
        <div class="detail-card">
          <div v-if="contractData.terminationSubmitter" class="detail-item">
            <span class="label">提交人：</span>
            <span class="value">{{ contractData.terminationSubmitter }}</span>
          </div>
          <div v-if="contractData.terminationTime" class="detail-item">
            <span class="label">解除日期：</span>
            <span class="value">{{
              parseTime(contractData.terminationTime, "{y}-{m}-{d}")
            }}</span>
          </div>
          <div v-if="contractData.terminationAgreement" class="detail-item">
            <span class="label">解除协议：</span>
            <span class="value">
              {{ contractData.terminationAgreement }}
              <el-button
                type="text"
                size="small"
                @click="viewFile(contractData.terminationAgreement)"
              >
                查看
              </el-button>
            </span>
          </div>
        </div>
      </div>

      <!-- 返回按钮 -->
      <div class="back-button-container">
        <el-button type="primary" @click="handleBack">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup name="ContractDetail">
import { ref, onMounted, watch, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getContract } from "@/api/system/contract";
import { getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";

// 获取路由和路由参数
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { lekang_contract_status } = proxy.useDict("lekang_contract_status");

// 数据状态
const loading = ref(false);
// 详情页脚本部分修改
const contractData = ref({
  elderly: {}, // 初始化嵌套对象
  sysUser: {}, // 初始化用户对象
});

// 组件挂载时可以执行其他初始化操作
onMounted(() => {
  console.log("合同详情页面已挂载");
});

// 获取合同详情
function loadContractDetail() {
  // 从路由参数获取合同ID
  const contractId = route.query.id;
  if (!contractId) {
    console.error("未找到合同ID");
    return;
  }

  // 添加日志记录当前路由参数
  console.log("路由参数:", route.query);

  // 首先检查是否有预加载数据
  if (route.query.preload) {
    try {
      // 尝试解析预加载数据
      const preloadedData = JSON.parse(route.query.preload);
      console.log("预加载数据:", preloadedData);

      // 深拷贝数据，确保嵌套对象存在
      contractData.value = JSON.parse(JSON.stringify(preloadedData));

      // 确保必要的嵌套对象存在
      if (!contractData.value.elderly) {
        contractData.value.elderly = {};
      }
      if (!contractData.value.sysUser) {
        contractData.value.sysUser = {};
      }

      // 特殊处理：如果预加载数据中没有老人信息，尝试从name和idCard字段获取
      if (!contractData.value.elderly.name && contractData.value.name) {
        contractData.value.elderly.name = contractData.value.name;
      }
      if (!contractData.value.elderly.idCard && contractData.value.idCard) {
        contractData.value.elderly.idCard = contractData.value.idCard;
      }

      console.log("使用预加载数据完成");
      return; // 已使用预加载数据，不需要再请求API
    } catch (e) {
      console.error("解析预加载数据失败：", e);
    }
  }

  // 如果没有预加载数据或解析失败，则请求API
  loading.value = true;
  getContract(contractId)
    .then((response) => {
      loading.value = false;
      console.log("API返回数据:", response.data);

      // 检查响应数据
      if (response && response.data) {
        // 深拷贝确保不影响原始数据
        contractData.value = JSON.parse(JSON.stringify(response.data));

        // 确保必要的嵌套对象存在
        if (!contractData.value.elderly) {
          contractData.value.elderly = {};
        }
        if (!contractData.value.sysUser) {
          contractData.value.sysUser = {};
        }

        // 特殊处理：从API返回数据中提取可能的老人信息
        if (!contractData.value.elderly.name && contractData.value.name) {
          contractData.value.elderly.name = contractData.value.name;
        }
        if (!contractData.value.elderly.idCard && contractData.value.idCard) {
          contractData.value.elderly.idCard = contractData.value.idCard;
        }
      } else {
        console.error("获取合同详情失败：响应数据格式不正确");
        ElMessage.error("获取合同详情失败");
      }
    })
    .catch((error) => {
      loading.value = false;
      console.error("获取合同详情出错：", error);
      ElMessage.error("获取合同详情出错");
    });
}

// 监听路由参数变化，当合同ID改变时重新加载数据
watch(
  () => route.query.id,
  (newId, oldId) => {
    console.log("合同ID变化:", oldId, "->", newId);
    if (newId) {
      loadContractDetail();
    }
  },
  { immediate: true }
); // 立即执行以加载初始数据

// 组件卸载时清理数据，避免内存泄漏
onUnmounted(() => {
  contractData.value = {};
  loading.value = false;
});

// 获取合同状态对应的标签类型
function getStatusType(status) {
  const typeMap = {
    0: "primary", // 未生效
    1: "success", // 生效中
    2: "warning", // 已失效
    3: "danger", // 已过期
  };
  return typeMap[status] || "info";
}

// 获取合同状态标签
function getStatusLabel(status) {
  const statusDict = lekang_contract_status.value || [];
  const statusItem = statusDict.find((item) => item.value === status);
  return statusItem ? statusItem.label : status || "-";
}

// 查看文件
function viewFile(fileName) {
  // 这里实现文件查看逻辑，通常是调用文件下载/预览接口
  proxy.download("system/contract/viewFile", { fileName: fileName }, fileName);
}

// 返回上一页
function handleBack() {
  // 使用go(-1)返回上一页，避免硬编码路由路径导致的404错误
  // 这种方式更加可靠，因为它不需要知道具体的路由路径
  router.go(-1);
}

// 时间格式化函数
function parseTime(time, pattern) {
  if (time == undefined || time == null || time == "") {
    return "";
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date = new Date(time);
  if (isNaN(date.getTime())) {
    return "";
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.detail-content {
  max-width: 800px;
  margin: 0 auto;
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-number {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  font-size: 12px;
  margin-right: 8px;
}

.section-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 500;
}

.detail-card {
  background-color: #fafafa;
  padding: 20px;
  border-radius: 6px;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
  min-height: 36px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  flex-shrink: 0;
}

.value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

.back-button-container {
  text-align: center;
  margin-top: 40px;
}

/* 确保标签样式正确 */
:deep(.el-tag) {
  font-size: 12px;
  padding: 0 10px;
  height: 24px;
  line-height: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .detail-content {
    padding: 15px;
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .label {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>